package com.gyp.feign;

import com.alibaba.fastjson.JSONObject;
import com.gyp.config.properties.IamConfig;
import com.gyp.manager.PersonManager;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.Map;
import java.util.Objects;

@Configuration
@RequiredArgsConstructor
@Slf4j

public class FeignRequestInterceptor implements RequestInterceptor {

    private final PersonManager personManager;

    private final IamConfig iamConfig;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String token = personManager.getToken();
        requestTemplate.header("X-Auth-Token", token);
        requestTemplate.header("X-Project-Id", iamConfig.getProjectId());
        String method = requestTemplate.method();
        Map<String, Collection<String>> headers = requestTemplate.headers();
        log.info("[华为云请求][地址]:{},[请求类型]:{},[请求头]:{}", requestTemplate.url(), method, JSONObject.toJSONString(headers));
        Map<String, Collection<String>> queries = requestTemplate.queries();
        if (Objects.nonNull(queries)) {
            log.info("[华为云请求][url参数]:{}", JSONObject.toJSONString(queries));
        }
        if (!requestTemplate.method().toLowerCase().equals("get")
                &&
                Objects.nonNull(requestTemplate.headers().get("Content-Type")) &&
                !requestTemplate
                        .headers().get("Content-Type").toString().contains("form-data")
        ) {
            byte[] bytes = requestTemplate.body();
            if (Objects.nonNull(bytes)) {
                String body = new String(bytes);
                log.info("[华为云请求][body参数]:{}", body);
            }

        }


    }





}
